<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <img :src="avatarUrl" alt="头像" />
    </div>
    <template #dropdown>
      <el-dropdown-menu width="100px">
        <el-dropdown-item @click="goUserCentreHandler()">
          <el-icon><User /></el-icon>个人中心
        </el-dropdown-item>
        <el-dropdown-item @click="openDrawer('editDateRef')">
          <el-icon><Lock /></el-icon>修改时间
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <EditDateDrawer ref="editDateRef" />
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { usePermissionStore } from "@/stores/modules/permission";
import { useGlobalStore } from "@/stores/modules/global";
import { ElMessageBox } from "element-plus";
import EditDateDrawer from "./EditDateDrawer.vue";
import { useKeepAliveStore, useTabsStore } from "@/stores";
import { logOutApi } from "@/api";
import defAva from "@/assets/images/avatar.jpg";
import { getEnv } from "@/utils/getEnv";

defineOptions({
  name: "Avatar"
});

const router = useRouter();
const useUser = useUserStore();
const usePermission = usePermissionStore();
const useTabs = useTabsStore();
const useKeepAlive = useKeepAliveStore();
const useGlobal = useGlobalStore();
const avatarUrl = computed(() =>
  useUser.userInfo && useUser.userInfo.avatar ? getEnv("VITE_PROXY") + useUser.userInfo.avatar : defAva
);

// 退出登录
const logout = () => {
  ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      // 1.执行退出登录接口
      const res = await logOutApi();
      if (res.code === 200) {
        // 清除缓存
        useKeepAlive.setKeepAliveName();
        // 清除缓存
        useUser.clearCacheHandler();
        usePermission.clearCacheHandler();
        sessionStorage.clear();
        useTabs.closeMultipleTab();
        useTabs.closeAllTabs();
        useGlobal.clearGlobalConfig();
        // 跳转登录页面
        router.go(0);
      } else {
        console.error(res.message);
      }
    })
    .catch((error) => {
      console.error(error);
    });
};

const editDateRef = ref<InstanceType<typeof EditDateDrawer> | null>(null);
const openDrawer = (ref: string) => {
  if (ref == "editDateRef") editDateRef.value?.openDrawer();
};

/**
 * @description 跳转用户中心
 */
const goUserCentreHandler = () => {
  router.push("/userCentre");
};
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
